package com.wly.frame.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.wly.frame.mvvm.base.BaseFragment
import com.wly.frame.mvvm.base.BaseViewModel
import me.xdj.view.MultiStateView
import java.lang.reflect.ParameterizedType

/**
 * author: wangliyun
 * date: 2022/3/23
 * description:
 */
abstract class BaseMVVMFragment<VM : BaseViewModel, VD : ViewDataBinding> : BaseFragment() {
    lateinit var mViewDataBinding: VD
    lateinit var mViewModel: VM


    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): ViewBinding? {
        mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
        mViewDataBinding.lifecycleOwner = this
        return mViewDataBinding
    }


    /**
     * 创建观察者
     */
    abstract fun initObserver()

    override fun getLayoutRes(): Int = 0

    override fun initData() {
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        initObserver()

        // 请求状态统一封装
        //TODO:根据具体业务需求场景 区分业务异常、其它异常  status 可以直接使用 data class 进行抽象管理 code/exception
        mViewModel.reqStatusLiveData.observe(this, { status ->
            when (status) {
                MultiStateView.STATE_LOADING -> showLoadingView()
                MultiStateView.STATE_EMPTY -> showEmptyView()
                MultiStateView.STATE_FAIL -> showFailView()
                MultiStateView.STATE_CONTENT -> showContentView()
                else -> {
                    Log.i("wangly", "请检查传入的状态值")
                }
            }
        })
    }

    fun showEmptyView() {
        multiStateView?.viewState = MultiStateView.STATE_EMPTY
    }

    fun showLoadingView() {
        multiStateView?.viewState = MultiStateView.STATE_LOADING
    }

    fun showFailView() {
        multiStateView?.viewState = MultiStateView.STATE_FAIL
    }

    fun showContentView() {
        multiStateView?.viewState = MultiStateView.STATE_CONTENT
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    /**
     * 获取当前类绑定的泛型ViewModel-clazz
     */
    @Suppress("UNCHECKED_CAST")
    fun <VM> getVmClazz(obj: Any): VM {
        return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
    }
}